package com.zego.wawaji.ui.center;

import android.text.TextUtils;

import com.zego.wawaji.base.log.PLogger;
import com.zego.wawaji.base.log.PSP;
import com.zego.wawaji.base.log.PToast;
import com.zego.wawaji.base.media.MediaConstant;
import com.zego.wawaji.base.module.ModuleMgr;
import com.zego.wawaji.base.observer.ModuleBase;
import com.zego.wawaji.base.observer.MsgMgr;
import com.zego.wawaji.base.observer.MsgType;
import com.zego.wawaji.base.observer.PObserver;
import com.zego.wawaji.base.utils.FileUtil;
import com.zego.wawaji.http.request.HttpResponse;
import com.zego.wawaji.http.request.RequestComplete;
import com.zego.wawaji.http.request.UrlParam;
import com.zego.wawaji.socket.IMProxy;
import com.zego.wawaji.third.zego.ZegoMgr;
import com.zego.wawaji.ui.bean.UpLoadResult;
import com.zego.wawaji.ui.bean.user.EditKey;
import com.zego.wawaji.ui.bean.user.UserDetail;
import com.zego.wawaji.ui.dialog.LoadingDialog;
import com.zego.wawaji.wawaji_client.util.PreferenceUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 个人中心管理类
 */
public class CenterMgr implements ModuleBase, PObserver {
    public static final String INFO_SAVE_KEY = "WAWAJI_INFO_KEY"; // 本地化个人资料key
    private static final String SETTING_SAVE_KEY = "WAWAJI_SETTING_KEY"; // 本地化设置key

    private UserDetail userDetail = null;

    @Override
    public void init() {
        MsgMgr.getInstance().attach(this);
    }

    @Override
    public void release() {
        MsgMgr.getInstance().detach(this);
    }

    @Override
    public void onMessage(String key, Object value) {
        switch (key) {
            case MsgType.MT_App_Login:
                if ((Boolean) value) {
                    IMProxy.getInstance().connect();//登录成功之后连接socket
                    ModuleMgr.getWawaMgr().reqWawaList(null); // 请求娃娃列表
                    reqMyInfo(new RequestComplete() {
                        @Override
                        public void onRequestComplete(HttpResponse response) {
                            if (!response.isCache() && response.isOk()) {
                                if (!ZegoMgr.isInitSuc)   // 还未初始化成功时，进行SDK初始化
                                    ZegoMgr.getInstance().initSDK();

                                UserDetail detail = (UserDetail) response.getBaseData();
                                ModuleMgr.getPushMgr().setJPushTag(detail.getUid());
                            }
                        }
                    });// 请求个人资料
                } else {
                    IMProxy.getInstance().logout();//退出登录的时候退出socket
//                    clearUserInfo();
                }
                break;

            case MsgType.MT_Update_MyInfo:
                reqMyInfo(null);// 请求个人资料
                break;
        }
    }

    /**
     * 用户签到
     */
    public void reqSign(final RequestComplete complete) {
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqSign, new HashMap<String, Object>(), new RequestComplete() {
            @Override
            public void onRequestComplete(HttpResponse response) {
                if (complete != null)
                    complete.onRequestComplete(response);
            }
        });
    }

    /**
     * 新用户注册奖励
     */
    public void reqRewardNew(final RequestComplete complete) {
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqRewardNew, new HashMap<String, Object>(), new RequestComplete() {
            @Override
            public void onRequestComplete(HttpResponse response) {
                if (complete != null)
                    complete.onRequestComplete(response);
            }
        });
    }

    /**
     * 获取我的个人资料
     */
    public UserDetail getMyInfo() {
        if (userDetail == null) {
            userDetail = new UserDetail();
            String result = PSP.getInstance().getString(INFO_SAVE_KEY, "");
            if (!TextUtils.isEmpty(result)) {
                userDetail.parseJson(result);
            }
        }
        return userDetail;
    }

    /**
     * 获取自己的个人资料
     */
    public void reqMyInfo(final RequestComplete complete) {
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqMyInfo, new HashMap<String, Object>(), new RequestComplete() {
            @Override
            public void onRequestComplete(HttpResponse response) {
                if (response.isOk()) {
                    userDetail = (UserDetail) response.getBaseData();
                    setMyInfo(response.getResString());         // 保存到SP
                    PreferenceUtil.getInstance().setUserID(String.valueOf(userDetail.getUid()));
                    if (TextUtils.isEmpty(userDetail.getNickname())) {
                        PreferenceUtil.getInstance().setUserName(String.valueOf(userDetail.getUid()));
                    } else {
                        PreferenceUtil.getInstance().setUserName(userDetail.getNickname());
                    }
                    if (!response.isCache()) {
                        MsgMgr.getInstance().sendMsg(MsgType.MT_MyInfo_Change, null);
                    }
                }
                if (complete != null) {
                    complete.onRequestComplete(response);
                }
            }
        });
    }

    /**
     * 保存个人信息Json串到SP
     */
    private void setMyInfo(String resultStr) {
        PSP.getInstance().put(INFO_SAVE_KEY, resultStr);
    }

    /**
     * 清除用户信息
     */
    public void clearUserInfo() {
        userDetail = null;
        setMyInfo("");
    }

    /**
     * 保存设置信息Json串到SP
     */
    private void putSettingPsp(String resultStr) {
        PSP.getInstance().put(SETTING_SAVE_KEY, resultStr);
    }

    /**
     * 修改个人信息
     */
    public void updateMyInfo(final HashMap<String, Object> params, final RequestComplete complete) {
        if (userDetail == null) return;
        params.put("Id", userDetail.getUid());
        ModuleMgr.getHttpMgr().reqJsonNoCacheHttp(UrlParam.reqUpdateInfo, params, new RequestComplete() {
            @Override
            public void onRequestComplete(HttpResponse response) {
                LoadingDialog.closeLoadingDialog(200);
                PToast.showShort(response.getMsg());
                if (complete != null) complete.onRequestComplete(response);
                if (response.isOk())
                    reqMyInfo(null);
            }
        });
    }

    /**
     * 上传头像
     *
     * @param url      图片本地地址
     * @param complete 上传完成回调
     */
    public void uploadAvatar(final String url, final RequestComplete complete) {
        if (FileUtil.isExist(url)) {
            ModuleMgr.getMediaMgr().sendHttpFile(MediaConstant.UPLOAD_TYPE_AVATAR, url, new RequestComplete() {
                @Override
                public void onRequestComplete(HttpResponse response) {
                    LoadingDialog.closeLoadingDialog();
                    FileUtil.deleteFile(url);

                    if (!response.isOk()) {
                        PToast.showShort(response.getMsg());
                        return;
                    }

                    UpLoadResult result = (UpLoadResult) response.getBaseData();
                    HashMap<String, Object> postParams = new HashMap<>();
                    // 拼接完整图片地址
                    postParams.put(EditKey.s_key_avatar, result.getFile_s_path());
                    updateMyInfo(postParams, new RequestComplete() {
                        @Override
                        public void onRequestComplete(HttpResponse response) {
                            if (complete != null) complete.onRequestComplete(response);
                        }
                    });
                }
            });
        } else {
            LoadingDialog.closeLoadingDialog();
            PToast.showShort("图片地址无效");
        }
    }

    /**
     * 获取用户列表
     */
    public void reqGetAddress(RequestComplete complete) {
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqGetAddress, new HashMap<String, Object>(), complete);
    }

    /**
     * 修改地址
     */
    public void reqUpdataAddress(long id, String name, String phone, String province, String city, String street, final RequestComplete complete) {
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("Uid", ModuleMgr.getCenterMgr().getMyInfo().getUid());
        jsonMap.put("Id", id);
        jsonMap.put("Province", province);
        jsonMap.put("City", city);
        jsonMap.put("ReceiverName", name);
        jsonMap.put("Street", street);
        jsonMap.put("Telphone", phone);
        ModuleMgr.getHttpMgr().reqJsonNoCacheHttp(UrlParam.reqUpdataAddress, jsonMap, new RequestComplete() {
            @Override
            public void onRequestComplete(HttpResponse response) {
                PToast.showShort(response.getMsg());
                if (response.isOk())
                    MsgMgr.getInstance().sendMsg(MsgType.MT_Updata_Address, null);
                if (complete != null)
                    complete.onRequestComplete(response);
            }
        });
    }

    /**
     * 修改默认地址地址
     */
    public void reqDefaultAddress(long addID, final RequestComplete complete, final boolean show) {
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("aid", addID);
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqDefaultAddress, jsonMap, new RequestComplete() {
            @Override
            public void onRequestComplete(HttpResponse response) {
                if (show)
                    PToast.showShort(response.getMsg());
                if (response.isOk())
                    MsgMgr.getInstance().sendMsg(MsgType.MT_Updata_Address, null);
                if (complete != null)
                    complete.onRequestComplete(response);
            }
        });
    }

    /**
     * 增加用户地址
     */
    public void reqAddAddress(String name, String phone, String province, String city, String street, final RequestComplete complete) {
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("Uid", ModuleMgr.getCenterMgr().getMyInfo().getUid());
        jsonMap.put("Id", 0);
        jsonMap.put("Province", province);
        jsonMap.put("City", city);
        jsonMap.put("ReceiverName", name);
        jsonMap.put("Street", street);
        jsonMap.put("Telphone", phone);
        ModuleMgr.getHttpMgr().reqJsonNoCacheHttp(UrlParam.reqAddAddress, jsonMap, new RequestComplete() {
            @Override
            public void onRequestComplete(HttpResponse response) {
                PToast.showShort(response.getMsg());
                if (response.isOk())
                    MsgMgr.getInstance().sendMsg(MsgType.MT_Updata_Address, null);
                if (complete != null)
                    complete.onRequestComplete(response);
            }
        });
    }

    /**
     * 删除地址
     */
    public void reqDeleAddress(long aid, final RequestComplete complete) {
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("aid", aid);
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqDeleAddress, jsonMap, new RequestComplete() {
            @Override
            public void onRequestComplete(HttpResponse response) {
                PToast.showShort(response.getMsg());
                if (response.isOk())
                    MsgMgr.getInstance().sendMsg(MsgType.MT_Updata_Address, null);
                if (complete != null)
                    complete.onRequestComplete(response);
            }
        });
    }
}